import { useState, useCallback } from 'react';
import { message } from 'antd';

interface PaginationParams {
  page?: number;
  limit?: number;
  [key: string]: unknown;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  error?: string;
}

interface UseDataFetchingOptions<T> {
  fetchFunction: (params?: PaginationParams) => Promise<ApiResponse<unknown>>;
  onSuccess?: (data: T[]) => void;
  onError?: (error: unknown) => void;
  successMessage?: string;
  errorMessage?: string;
}

interface UseDataFetchingReturn<T> {
  data: T[];
  loading: boolean;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
    totalPages: number;
  };
  fetchData: (params?: PaginationParams) => Promise<void>;
  setData: (data: T[]) => void;
  setLoading: (loading: boolean) => void;
  setPagination: (pagination: { current: number; pageSize: number; total: number; totalPages: number }) => void;
}

export function useDataFetching<T>({
  fetchFunction,
  onSuccess,
  onError,
  successMessage,
  errorMessage = '获取数据失败'
}: UseDataFetchingOptions<T>): UseDataFetchingReturn<T> {
  const [data, setData] = useState<T[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  });

  const fetchData = useCallback(async (params?: PaginationParams) => {
    setLoading(true);
    try {
      const response = await fetchFunction(params);
      if (response.success) {
        const responseData = response.data as Record<string, unknown>;
        
        // 处理不同的数据结构
        if (responseData && 'articles' in responseData && Array.isArray(responseData.articles)) {
          setData(responseData.articles as T[]);
        } else if (responseData && 'cases' in responseData && Array.isArray(responseData.cases)) {
          setData(responseData.cases as T[]);
        } else if (Array.isArray(responseData)) {
          setData(responseData as T[]);
        } else {
          setData([]);
        }

        // 设置分页信息
        if (responseData && 'page' in responseData && typeof responseData.page === 'number') {
          setPagination({
            current: responseData.page,
            pageSize: (responseData.limit as number) || 10,
            total: (responseData.total as number) || 0,
            totalPages: (responseData.totalPages as number) || 0
          });
        }

        const resultData = responseData?.articles || responseData?.cases || responseData;
        onSuccess?.(Array.isArray(resultData) ? resultData as T[] : []);
        if (successMessage) {
          message.success(successMessage);
        }
      }
    } catch (error) {
      console.error(errorMessage, error);
      message.error(errorMessage);
      onError?.(error);
    } finally {
      setLoading(false);
    }
  }, [fetchFunction, onSuccess, onError, successMessage, errorMessage]);

  return {
    data,
    loading,
    pagination,
    fetchData,
    setData,
    setLoading,
    setPagination
  };
}